﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Yz.Core.Extensions;
using Yz.DB.EFCore.Dal;
using Yz.Model.Constants;
using Yz.Model.Entities;
using Yz.Model.Views;

namespace Yz.Manage.Controllers
{
    [Authorize(Roles = UserRoleName.CompanyAdmin)]
    public class SupplementSettingController : BaseController
    {
        private readonly IDbAccess<SupplementSetting> _supplementSettingDbAccess;
        public SupplementSettingController(IDbAccess<SupplementSetting> supplementSettingDbAccess)
        {
            _supplementSettingDbAccess = supplementSettingDbAccess;
        }
        public async Task<IActionResult> Index()
        {
            int companyId = base.CompanyId;
            var sptSet = await _supplementSettingDbAccess.GetModelAsync<VmSupplementSetting>(p => p.CompanyId == companyId);
            if (sptSet == null)
            {
                var endTime = DateTime.Now.AddDays(15);
                await _supplementSettingDbAccess.AddAsync(new SupplementSetting()
                {
                    CompanyId = companyId
                }, p => p.CompanyId == companyId);
                sptSet = await _supplementSettingDbAccess.GetModelAsync<VmSupplementSetting>(p => p.CompanyId == companyId);
            }
            ViewBag.sptSet = sptSet.ToJsonStr();
            return View();
        }
        /// <summary>
        /// 保存补录设置
        /// </summary>
        /// <param name="supplementSetting"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Save(SupplementSetting supplementSetting)
        {
            int companyId = base.CompanyId;
            var dtNow = DateTime.Now;
            var retCode = await _supplementSettingDbAccess.UpdateAsync(
                p => p.SetProperty(q => q.ApplyCount, supplementSetting.ApplyCount)
                .SetProperty(q => q.EndTime, supplementSetting.EndTime)
                .SetProperty(q => q.TotalCount, supplementSetting.TotalCount)
                .SetProperty(q => q.UpdateTime, dtNow), p => p.Id == supplementSetting.Id);
            ; return Json(retCode.ToVmReturn());
        }
    }
}